﻿using System.Collections;
using UnityEngine;

public class AudioDeviceHandler : MonoBehaviour
{
    void Start()
    {
        // 注册Unity音频配置变化事件
        AudioSettings.OnAudioConfigurationChanged += OnAudioConfigChanged;
        //StartCoroutine(CheckAudioDevicePeriodically());
    }

    protected void OnDestroy()
    {
        AudioSettings.OnAudioConfigurationChanged -= OnAudioConfigChanged;
    }
    IEnumerator CheckAudioDevicePeriodically()
    {
        while (true)
        {
            yield return new WaitForSeconds(1.0f);
            // 调用方案2的检测逻辑
            CheckAudioDeviceChanged();
        }
    }

    private void Update()
    {

    }
    // Unity音频配置变化回调
    private void OnAudioConfigChanged(bool deviceChanged)
    {
        if (deviceChanged)
            RestoreAudioPlayback();
    }

    // 手动恢复音频播放
    public void RestoreAudioPlayback()
    {
        AudioListener[] listeners = FindObjectsByType<AudioListener>(FindObjectsInactive.Include, FindObjectsSortMode.None);
        foreach (AudioListener listener in listeners)
        {
            listener.enabled = false;
            listener.enabled = true;
        }
        // 重新播放所有 AudioSource
        AudioSource[] sources = FindObjectsByType<AudioSource>(FindObjectsInactive.Include, FindObjectsSortMode.None);
        foreach (AudioSource source in sources)
        {
            if (source.isPlaying)
            {
                float timeElpase = source.time;
                source.Stop();
                source.time = timeElpase;
                source.Play();
            }
        }
    }
    private string _prevAudioDeviceName;
    private bool _prevBluetoothState;
    private void CheckAudioDeviceChanged()
    {
#if UNITY_ANDROID
        try
        {
            using (var audioManager = GetAudioManager())
            {
                string currentDevice = audioManager.Call<string>("getProperty", "android.media.property.OUTPUT_DEVICE_NAME");
                bool isBluetoothOn = audioManager.Call<bool>("isBluetoothA2dpOn");

                if (currentDevice != _prevAudioDeviceName || isBluetoothOn != _prevBluetoothState)
                {
                    XKLog.LogError($"音频设备变更检测: 前设备={_prevAudioDeviceName} 新设备={currentDevice} | 前蓝牙状态={_prevBluetoothState} 新状态={isBluetoothOn}");

                    try
                    {
                        audioManager.Call("setBluetoothA2dpOn", isBluetoothOn); // 关键调用
                        _prevAudioDeviceName = currentDevice;
                        _prevBluetoothState = isBluetoothOn;

                        XKLog.LogError($"开始恢复音频播放...");
                        RestoreAudioPlayback();
                    }
                    catch (System.Exception e)
                    {
                        XKLog.LogError($"蓝牙音频设置失败: {e.Message}");
                    }
                }
            }
        }
        catch (System.Exception e)
        {
            XKLog.LogError("检测设备失败: " + e.Message);
        }
#endif
    }

    private AndroidJavaObject GetAudioManager()
    {
        using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        using (var activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
        {
            return activity.Call<AndroidJavaObject>("getSystemService", "audio");
        }
    }

}
